package org.jeecg.wechat2;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.riversoft.weixin.app.base.AppSetting;
import com.riversoft.weixin.app.user.SessionKey;
import com.riversoft.weixin.app.user.Users;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.constant.enums.MainErrorEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.wechat.WxAppletConfig;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.common.CommonUtil;
import org.jeecg.modules.custom.entity.MtCustorm;
import org.jeecg.modules.custom.service.IMtCustomEquipService;
import org.jeecg.modules.custom.service.IMtCustormService;
import org.jeecg.modules.engineer.entity.MtEngineer;
import org.jeecg.modules.engineer.service.IMtEngineerService;
import org.jeecg.modules.equipment.service.IMtEquipService;
import org.jeecg.modules.equipment.service.IMtEquipTypeService;
import org.jeecg.modules.mq.service.OrderProducerService;
import org.jeecg.modules.order.entity.*;
import org.jeecg.modules.order.service.*;
import org.jeecg.modules.order.vo.MtRepairDisposePage;
import org.jeecg.modules.order.vo.MtRepairOrderPage;
import org.jeecg.modules.providers.entity.MtServiceProviders;
import org.jeecg.modules.providers.service.IMtServiceProvidersService;
import org.jeecg.modules.station.entity.MtServiceStation;
import org.jeecg.modules.station.service.IMtServiceStationService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.model.SysLoginModel;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.util.PositionUtil;
import org.jeecg.modules.wx.entity.MtUnionWx;
import org.jeecg.modules.wx.entity.WxLogin;
import org.jeecg.modules.wx.service.IMtUnionWxService;
import org.jeecg.wechat.request.*;
import org.jeecg.wechat.vo.UserInfoVo;
import org.jeecg.wechat2.request.*;
import org.jeecg.wechat2.request.WxRepairDispatchRequest;
import org.jeecg.wechat2.vo.WxUserInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;


/**
 * @description: 报修微信小程序接口
 * @program:
 * @author: cheng
 * @date: 2022-09-09 16:21
 **/
@Api(tags = "报修微信小程序接口-v2")
@RestController
@RequestMapping("/maintain/wechat/v2")
@Slf4j
public class WeChat {

    private final ISysUserService sysUserService;
    private final WxAppletConfig wxAppletConfig;
    private final IMtUnionWxService mtUnionWxService;
    private final CommonAPI commonAPI;
    private final IMtServiceProvidersService mtServiceProvidersService;
    private final IMtServiceStationService mtServiceStationService;
    private final IMtEngineerService mtEngineerService;
    private final IMtCustormService mtCustormService;
    private final IMtRepairOrderService mtRepairOrderService;
    private final IMtRepairDispatchService mtRepairDispatchService;
    private final IMtRepairScheduleService mtRepairScheduleService;
    private final IMtRepairEquipService mtRepairEquipService;
    private final IMtRepairDisposeService mtRepairDisposeService;
    private final IMtRepairFeedbackService mtRepairFeedbackService;
    private final IMtRepairVisitService mtRepairVisitService;
    @Resource
    private BaseCommonService baseCommonService;

    @Autowired
    private RedisUtil redisUtil;
    /**
     * 本地：local minio：minio 阿里：alioss
     */
    @Value(value = "${jeecg.uploadType}")
    private String uploadType;
    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    public WeChat(IMtUnionWxService mtUnionWxService, ISysUserService sysUserService, WxAppletConfig wxAppletConfig, IMtRepairVisitService mtRepairVisitService, CommonAPI commonAPI, IMtServiceProvidersService mtServiceProvidersService, IMtServiceStationService mtServiceStationService, IMtRepairFeedbackService mtRepairFeedbackService, IMtEngineerService mtEngineerService, IMtRepairEquipService mtRepairEquipService, IMtRepairDisposeService mtRepairDisposeService, IMtCustormService mtCustormService, IMtRepairOrderService mtRepairOrderService, IMtRepairDispatchService mtRepairDispatchService, IMtRepairScheduleService mtRepairScheduleService) {
        this.mtUnionWxService = mtUnionWxService;
        this.sysUserService = sysUserService;
        this.wxAppletConfig = wxAppletConfig;
        this.mtRepairVisitService = mtRepairVisitService;
        this.commonAPI = commonAPI;
        this.mtServiceProvidersService = mtServiceProvidersService;
        this.mtServiceStationService = mtServiceStationService;
        this.mtRepairFeedbackService = mtRepairFeedbackService;
        this.mtEngineerService = mtEngineerService;
        this.mtRepairEquipService = mtRepairEquipService;
        this.mtRepairDisposeService = mtRepairDisposeService;
        this.mtCustormService = mtCustormService;
        this.mtRepairOrderService = mtRepairOrderService;
        this.mtRepairDispatchService = mtRepairDispatchService;
        this.mtRepairScheduleService = mtRepairScheduleService;
    }

    /**
     * 报修微信小程序用户登录获取openid
     *
     * @param wxUserLoginRequest
     * @return
     */
    @ApiOperation(value = "wechat-报修微信小程序用户登录获取openid", notes = "wechat-报修微信小程序用户登录获取openid")
    @PostMapping("/wcLogin")
    public Result<?> wcLogin(@RequestBody WxUserLoginRequest wxUserLoginRequest) {
        SessionKey sessionKey = Users.with(new AppSetting(wxAppletConfig.getAppId(), wxAppletConfig.getSecret())).code2Session(wxUserLoginRequest.getCode());
        return Result.OK(sessionKey.getOpenId());
    }

    /**
     * 报修微信小程序用户绑定
     *
     * @param wxLogin
     * @return
     */
    @ApiOperation(value = "wechat-报修微信小程序用户绑定", notes = "wechat-报修微信小程序用户绑定")
    @PostMapping("/bindWeChat")
    public Result<JSONObject> bindWeChat(@RequestBody WxLogin wxLogin) throws Exception {
        log.info("绑定-wxLogin:{}", wxLogin);
        String username = wxLogin.getUsername();
        String password = wxLogin.getPassword();
        String openId = wxLogin.getOpenId();
        SysUser loginUser;
        //判定该微信用户是否已经存在绑定记录
        List<SysUser> loginUserList = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getOpenid, openId));
        Result<JSONObject> result = new Result<JSONObject>();
        // 用户未绑定
        if (CollectionUtils.isEmpty(loginUserList)) {
            //1. 校验用户是否有效
            SysUser sysUser = sysUserService.getUserByName(username);
            result = sysUserService.checkUserIsEffective(sysUser);
            if (!result.isSuccess()) {
                return result;
            }
            //2. 校验用户名或密码是否正确
            String userpassword = PasswordUtil.encrypt(username, password, sysUser.getSalt());
            String syspassword = sysUser.getPassword();
            if (!syspassword.equals(userpassword)) {
                result.error500("用户名或密码错误");
                return result;
            }
            // 保存对外唯一标识
            sysUser.setOpenid(openId);
            sysUserService.updateById(sysUser);
            loginUser = sysUser;
        } else {
            loginUser = loginUserList.get(0);
        }
        JSONObject obj = new JSONObject();
        //用户登录信息
        obj.put("userInfo", loginUser);

        // 生成token
        String token = JwtUtil.sign(username, loginUser.getPassword());
        // 设置超时时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);

        //token 信息
        obj.put("token", token);
        result.setResult(obj);
        result.setSuccess(true);
        result.setCode(200);
        baseCommonService.addLog("用户名: " + username + ",登录成功[移动端]！", CommonConstant.LOG_TYPE_1, null);
        return result;
    }

    /**
     * 报修微信小程序用户解除绑定
     *
     * @param
     * @return
     */
    @ApiOperation(value = "wechat-报修微信小程序用户解除绑定", notes = "wechat-报修微信小程序用户解除绑定")
    @PostMapping("/unBindWeChat")
    public Result<?> unBindWeChat() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //判定该微信用户是否已经存在绑定记录
        if (Objects.isNull(loginUser.getOpenid())) {
            return Result.error(500, "用户暂未绑定，不可进行解绑操作！");
        }
        //登录用户为工程师
        if (loginUser.getUserType() == 3) {
            MtEngineer mtEngineer = mtEngineerService.getById(loginUser.getLinkId());
            if (Objects.isNull(mtEngineer)) {
                return Result.error(MainErrorEnum.ENGINEER_IS_NULL.getCode(), MainErrorEnum.ENGINEER_IS_NULL.getMsg());
            }
        }
        //登录用户为客户
        else if (loginUser.getUserType() == 4) {
            MtCustorm mtCustorm = mtCustormService.getById(loginUser.getLinkId());
            if (Objects.isNull(mtCustorm)) {
                return Result.error(MainErrorEnum.CUSTOM_IS_NULL.getCode(), MainErrorEnum.CUSTOM_IS_NULL.getMsg());
            }
        }
        if (sysUserService.removeOpenId(loginUser.getId())) {
            return Result.error(500, "用户解绑操作失败，请重试！");
        }
        return Result.ok("解除绑定操作成功！");
    }

    /**
     * 根据openid获取用户基本信息
     *
     * @param openId
     * @return userInfoVo
     */
    @ApiOperation(value = "wechat-根据openid获取用户基本信息", notes = "wechat-根据openid获取用户基本信息")
    @GetMapping("/getInfoByOpenId")
    public Result<WxUserInfoVo> getInfoByOpenId(@RequestParam("openId") @Validated @NotBlank(message = "用户openId不能为空") String openId) {
        if (StrUtil.isBlank(openId)) {
            return Result.error(MainErrorEnum.OPENID_NOT_NULL.getCode(), MainErrorEnum.OPENID_NOT_NULL.getMsg());
        }
        SysUser loginUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOpenid, openId), false);
        if (Objects.isNull(loginUser)) {
            return Result.error(MainErrorEnum.USER_NOT_BIND.getCode(), MainErrorEnum.USER_NOT_BIND.getMsg());
        }
        WxUserInfoVo wxUserInfoVo = new WxUserInfoVo();
        //登录用户为工程师
        if (loginUser.getUserType() == 3) {
            MtEngineer mtEngineer = mtEngineerService.getById(loginUser.getLinkId());
            // 工程师信息为空
            if (Objects.isNull(mtEngineer)) {
                return Result.error(MainErrorEnum.ENGINEER_IS_NULL.getCode(), MainErrorEnum.ENGINEER_IS_NULL.getMsg());
            }

            MtServiceProviders serviceProviders = mtServiceProvidersService.getById(mtEngineer.getProviderId());
            // 工作站信息为空
            if (Objects.isNull(serviceProviders)){
                return Result.error(MainErrorEnum.PROVIDER_IS_NULL.getCode(),MainErrorEnum.PROVIDER_IS_NULL.getMsg());
            }

            MtServiceStation serviceStation = mtServiceStationService.getById(mtEngineer.getStationId());
            // 工作站信息为空
            if (Objects.isNull(serviceStation)){
                return Result.error(MainErrorEnum.STATION_IS_NULL.getCode(),MainErrorEnum.STATION_IS_NULL.getMsg());
            }

            // 用户信息数据装配
            wxUserInfoVo.setWeiXinName(mtEngineer.getEngineerName())
                    .setUnionType(loginUser.getUserType().toString())
                    .setCoordinate(serviceStation.getCoordinate())
                    .setOrgCode(mtEngineer.getSysOrgCode())
                    .setLinkPhone(mtEngineer.getEngineerMobile())
                    .setMtServiceProviders(serviceProviders)
                    .setMtServiceStation(serviceStation);
        }
        //登录用户为客户
        else if (loginUser.getUserType() == 4) {
            MtCustorm mtCustorm = mtCustormService.getById(loginUser.getLinkId());
            // 客户信息为空
            if (Objects.isNull(mtCustorm)) {
                return Result.error(MainErrorEnum.CUSTOM_IS_NULL.getCode(), MainErrorEnum.CUSTOM_IS_NULL.getMsg());
            }
            // 未分配工作站
            if (StrUtil.isBlank(mtCustorm.getStationId())){
                return Result.error(MainErrorEnum.CUSTOM_NO_PROVIDER.getCode(),MainErrorEnum.CUSTOM_NO_PROVIDER.getMsg());
            }

            MtServiceProviders serviceProviders = mtServiceProvidersService.getById(mtCustorm.getProviderId());
            // 工作站信息为空
            if (Objects.isNull(serviceProviders)){
                return Result.error(MainErrorEnum.PROVIDER_IS_NULL.getCode(),MainErrorEnum.PROVIDER_IS_NULL.getMsg());
            }

            MtServiceStation serviceStation = mtServiceStationService.getById(mtCustorm.getStationId());
            // 工作站信息为空
            if (Objects.isNull(serviceStation)){
                return Result.error(MainErrorEnum.STATION_IS_NULL.getCode(),MainErrorEnum.STATION_IS_NULL.getMsg());
            }
            // 用户信息数据装配
            wxUserInfoVo.setUnionType(loginUser.getUserType().toString())
                    .setWeiXinName(mtCustorm.getCustormName())
                    .setCoordinate(mtCustorm.getCrood())
                    .setOrgCode(mtCustorm.getSysOrgCode())
                    .setLinkPhone(mtCustorm.getLinkPhone())
                    .setMtServiceProviders(serviceProviders)
                    .setMtServiceStation(serviceStation);
        }
        return Result.OK(wxUserInfoVo);
    }

    /**
     * 文件上传统一方法
     *
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value = "wechat-文件上传统一方法", notes = "wechat-文件上传统一方法")
    @PostMapping(value = "/upload")
    public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
        Result<?> result = new Result<>();
        String savePath = "";
        String bizPath = request.getParameter("biz");

        //LOWCOD-2580 sys/common/upload接口存在任意文件上传漏洞
        if (oConvertUtils.isNotEmpty(bizPath)) {
            if (bizPath.contains(SymbolConstant.SPOT_SINGLE_SLASH) || bizPath.contains(SymbolConstant.SPOT_DOUBLE_BACKSLASH)) {
                throw new JeecgBootException("上传目录bizPath，格式非法！");
            }
        }

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获取上传文件对象
        MultipartFile file = multipartRequest.getFile("file");
        if (oConvertUtils.isEmpty(bizPath)) {
            if (CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)) {
                //未指定目录，则用阿里云默认目录 upload
                bizPath = "upload";
                //result.setMessage("使用阿里云文件上传时，必须添加目录！");
                //result.setSuccess(false);
                //return result;
            } else {
                bizPath = "";
            }
        }
        if (CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)) {
            //update-begin-author:lvdandan date:20200928 for:修改JEditor编辑器本地上传
            savePath = this.uploadLocal(file, bizPath);
            //update-begin-author:lvdandan date:20200928 for:修改JEditor编辑器本地上传
            /**  富文本编辑器及markdown本地上传时，采用返回链接方式
             //针对jeditor编辑器如何使 lcaol模式，采用 base64格式存储
             String jeditor = request.getParameter("jeditor");
             if(oConvertUtils.isNotEmpty(jeditor)){
             result.setMessage(CommonConstant.UPLOAD_TYPE_LOCAL);
             result.setSuccess(true);
             return result;
             }else{
             savePath = this.uploadLocal(file,bizPath);
             }
             */
        } else {
            //update-begin-author:taoyan date:20200814 for:文件上传改造
            savePath = CommonUtils.upload(file, bizPath, uploadType);
            //update-end-author:taoyan date:20200814 for:文件上传改造
        }
        if (oConvertUtils.isNotEmpty(savePath)) {
            result.setMessage(savePath);
            result.setSuccess(true);
        } else {
            result.setMessage("上传失败！");
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 本地文件上传
     *
     * @param mf      文件
     * @param bizPath 自定义路径
     * @return
     */
    private String uploadLocal(MultipartFile mf, String bizPath) {
        try {
            String ctxPath = uploadpath;
            String fileName = null;
            File file = new File(ctxPath + File.separator + bizPath + File.separator);
            if (!file.exists()) {
                // 创建文件根目录
                file.mkdirs();
            }
            // 获取文件名
            String orgName = mf.getOriginalFilename();
            orgName = CommonUtils.getFileName(orgName);
            if (orgName.indexOf(SymbolConstant.SPOT) != -1) {
                fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
            } else {
                fileName = orgName + "_" + System.currentTimeMillis();
            }
            String savePath = file.getPath() + File.separator + fileName;
            File savefile = new File(savePath);
            FileCopyUtils.copy(mf.getBytes(), savefile);
            String dbpath = null;
            if (oConvertUtils.isNotEmpty(bizPath)) {
                dbpath = bizPath + File.separator + fileName;
            } else {
                dbpath = fileName;
            }
            if (dbpath.contains(SymbolConstant.DOUBLE_BACKSLASH)) {
                dbpath = dbpath.replace(SymbolConstant.DOUBLE_BACKSLASH, SymbolConstant.SINGLE_SLASH);
            }
            return dbpath;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return "";
    }


    /**
     * 分页列表查询
     *
     * @param mtRepairOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "wechat-分页列表查询", notes = "wechat-分页列表查询")
    @GetMapping(value = "/orderPageList")
    public Result<IPage<MtRepairOrder>> orderPageList(MtRepairOrder mtRepairOrder,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) {
        QueryWrapper<MtRepairOrder> queryWrapper = QueryGenerator.initQueryWrapper(mtRepairOrder, req.getParameterMap());
        Page<MtRepairOrder> page = new Page<MtRepairOrder>(pageNo, pageSize);
        // 获取登录工程师信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        // 用户为平台管理员
        if (sysUser.getUserType() == 0) {
            IPage<MtRepairOrder> pageList = mtRepairOrderService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
        // 用户为服务商
        else if (sysUser.getUserType() == 1) {
            MtServiceProviders loginProviders = mtServiceProvidersService.getOne(new LambdaQueryWrapper<MtServiceProviders>()
                    .eq(MtServiceProviders::getUserId, loginUser.getUsername()));
            if (Objects.isNull(loginProviders)) {
                return Result.error("未找到对应服务商");
            }
            queryWrapper.lambda().eq(MtRepairOrder::getProviderId, loginProviders.getId());
        }
        // 用户为工作站
        else if (sysUser.getUserType() == 2) {
            MtServiceStation loginStation = mtServiceStationService.getOne(new LambdaQueryWrapper<MtServiceStation>()
                    .eq(MtServiceStation::getUserId, loginUser.getUsername()));
            if (Objects.isNull(loginStation)) {
                return Result.error("未找到对应工作站");
            }
            queryWrapper.lambda().in(MtRepairOrder::getStationId, loginStation.getId());
        }
        // 用户为工程师
        else if (sysUser.getUserType() == 3) {
            MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                    .eq(MtEngineer::getUserId, loginUser.getUsername()));
            if (Objects.isNull(loginEngineer)) {
                return Result.error("未找到对应工程师");
            }
            // 获取工程师下属工单信息
            List<MtRepairDispatch> repairDispatchList = mtRepairDispatchService.list(new LambdaQueryWrapper<MtRepairDispatch>()
                    .eq(MtRepairDispatch::getEngineerId, loginEngineer.getId()));
            List<String> orderIds = repairDispatchList.stream().map(MtRepairDispatch::getOrderId).collect(Collectors.toList());
            queryWrapper.lambda().in(MtRepairOrder::getId, orderIds);
        }
        // 用户为客户
        else if (sysUser.getUserType() == 4) {
            MtCustorm loginCustorm = mtCustormService.getOne(new LambdaQueryWrapper<MtCustorm>()
                    .eq(MtCustorm::getUserId, loginUser.getUsername()));
            if (Objects.isNull(loginCustorm)) {
                return Result.error("未找到对应商户");
            }
            queryWrapper.lambda().eq(MtRepairOrder::getCustomId, loginCustorm.getId());
        }
        // 其他
        else {
            return Result.error("该用户无权查看");
        }
        IPage<MtRepairOrder> pageList = mtRepairOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 通过id查询工单
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "工单表-通过id查询")
    @ApiOperation(value = "wechat-通过id查询工单", notes = "wechat-通过id查询工单")
    @GetMapping(value = "/queryById")
    public Result<MtRepairOrder> queryById(@RequestParam(name = "id", required = true) String id) {
        MtRepairOrder repairOrder = mtRepairOrderService.getById(id);
        if (Objects.isNull(repairOrder)) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(repairOrder);
    }

    /**
     * 通过id查询派工记录
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "通过id查询派工记录", notes = "wechat-通过id查询派工记录")
    @GetMapping(value = "/queryMtRepairDispatchByOrderId")
    public Result<List<MtRepairDispatch>> queryMtRepairDispatchByOrderId(@RequestParam(name = "id", required = true) String id) {
        List<MtRepairDispatch> mtRepairDispatchList = mtRepairDispatchService.list(new LambdaQueryWrapper<MtRepairDispatch>().eq(MtRepairDispatch::getOrderId, id));
        return Result.OK(mtRepairDispatchList);
    }

    /**
     * 通过id查询设备记录
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "通过id查询设备记录", notes = "wechat-通过id查询设备记录")
    @GetMapping(value = "/queryMtRepairEquipByOrderId")
    public Result<List<MtRepairEquip>> queryMtRepairEquipByOrderId(@RequestParam(name = "id", required = true) String id) {
        List<MtRepairEquip> mtRepairEquipList = mtRepairEquipService.list(new LambdaQueryWrapper<MtRepairEquip>().eq(MtRepairEquip::getOrderId, id));
        return Result.OK(mtRepairEquipList);
    }

    /**
     * 通过id查询进度记录
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "通过id查询进度记录", notes = "wechat-通过id查询进度记录")
    @GetMapping(value = "/queryMtRepairScheduleByOrderId")
    public Result<List<MtRepairSchedule>> queryMtRepairScheduleByOrderId(@RequestParam(name = "id", required = true) String id) {
        List<MtRepairSchedule> mtRepairScheduleList = mtRepairScheduleService.list(new LambdaQueryWrapper<MtRepairSchedule>().eq(MtRepairSchedule::getOrderId, id));
        return Result.OK(mtRepairScheduleList);
    }

    /**
     * 通过id查询评价记录
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "通过id查询评价记录", notes = "wechat-通过id查询评价记录")
    @GetMapping(value = "/queryMtRepairFeedbackByOrderId")
    public Result<List<MtRepairFeedback>> queryMtRepairFeedbackByOrderId(@RequestParam(name = "id", required = true) String id) {
        List<MtRepairFeedback> mtRepairFeedbackList = mtRepairFeedbackService.list(new LambdaQueryWrapper<MtRepairFeedback>().eq(MtRepairFeedback::getOrderId, id));
        return Result.OK(mtRepairFeedbackList);
    }

    /**
     * 通过id查询处理记录
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "通过id查询处理记录", notes = "wechat-通过id查询处理记录")
    @GetMapping(value = "/queryMtRepairDisposeByOrderId")
    public Result<List<MtRepairDispose>> queryMtRepairDisposeByOrderId(@RequestParam(name = "id", required = true) String id) {
        List<MtRepairDispose> mtRepairDisposeList = mtRepairDisposeService.list(new LambdaQueryWrapper<MtRepairDispose>().eq(MtRepairDispose::getOrderId, id));
        return Result.OK(mtRepairDisposeList);
    }

    /**
     * 通过id查询回访记录
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "通过id查询回访记录", notes = "wechat-通过id查询回访记录")
    @GetMapping(value = "/queryMtRepairVisitByOrderId")
    public Result<List<MtRepairVisit>> queryMtRepairVisitByOrderId(@RequestParam(name = "id", required = true) String id) {
        List<MtRepairVisit> mtRepairVisitList = mtRepairVisitService.list(new LambdaQueryWrapper<MtRepairVisit>().eq(MtRepairVisit::getOrderId, id));
        return Result.OK(mtRepairVisitList);
    }

    /**
     * 客户报修
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "wechat-客户报修", notes = "wechat-客户报修")
    @PostMapping(value = "/repair")
    public Result<String> repair(@RequestBody WxRepairRequest request) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        // 获取当前客户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MtCustorm loginCustorm = mtCustormService.getOne(new LambdaQueryWrapper<MtCustorm>()
                .eq(MtCustorm::getLinkPhone, loginUser.getUsername()));
        if (Objects.isNull(loginCustorm)) {
            return Result.error("登录客户不存在");
        }
        //验证客户归属的服务商是否存在
        if (StrUtil.isBlank(loginCustorm.getProviderId())) {
            return Result.error("客户未设置服务商！");
        }
        //验证客户是否分配服务站
        if (StrUtil.isBlank(loginCustorm.getStationId())) {
            return Result.error("客户未分配服务站！");
        }

        // 工单信息数据装配
        mtRepairOrderPage.setMtRepairDispatchList(new ArrayList<>());
        MtRepairOrder mtRepairOrder = new MtRepairOrder();
        mtRepairOrder.setOrderNo(CommonUtil.createNo("C"))// 生成工单号
                .setOrderSource(request.getOrderSource())//来源
                .setSkillType("维修")// 工单类型默认值：维修
                .setProcessingStatus("0")// 处理状态默认值：已受理
                .setCustomId(loginCustorm.getId())// 客户id
                .setLinkMan(request.getLinkMan())//联系人
                .setLinkMobile(request.getLinkMobile())//联系电话
                .setRemarks(request.getRemarks())//问题描述
                .setBackStatus("0")// 反馈状态默认值：未反馈
                .setProblemPhoto(request.getProblemPhoto())//照片
                .setProviderId(loginCustorm.getProviderId())// 服务商
                .setStationId(loginCustorm.getStationId());// 服务站
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 工单进度数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(0)//进度状态：创建
                .setScheduleTime(DateUtil.date());//进度时间
        //进度描述
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + "客户：" + loginCustorm.getCustormName()
                + "创建了" + mtRepairOrder.getSkillType() + "工单");
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        // 保存工单数据
        mtRepairOrderService.saveMain(mtRepairOrder, mtRepairOrderPage.getMtRepairDispatchList(), mtRepairOrderPage.getMtRepairEquipList(), mtRepairOrderPage.getMtRepairScheduleList(), mtRepairOrderPage.getMtRepairFeedbackList(), mtRepairOrderPage.getMtRepairDisposeList());
        log.info("已保存订单数据：mtRepairOrderPage:{}", JSONObject.toJSONString(mtRepairOrderPage));
        return Result.OK("信息已提交，请关注进一步的处理结果！");
    }


    /**
     * 自动派工
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "wechat-自动派工", notes = "wechat-自动派工")
    @PutMapping(value = "/autoDispatch")
    public Result<String> autoDispatch(@RequestParam(name = "id", required = true) String id) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        // 筛选出工单数最少的工程师
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(id);
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应数据");
        }
        List<MtEngineer> engineerList = mtEngineerService.list(new LambdaQueryWrapper<MtEngineer>()
                .eq(MtEngineer::getStationId, mtRepairOrder.getStationId()));
        if (engineerList.isEmpty()) {
            return Result.error("工作站下暂无工程师");
        }
        for (MtEngineer engineer : engineerList) {
            engineer.setOrderNum(mtRepairOrderService.getProcessingListByEngineer(engineer.getId()).size());
        }
        Integer minNum = engineerList.stream()
                .map(MtEngineer::getOrderNum)
                .min(Integer::compareTo).orElse(0);
        List<MtEngineer> dispatchEngineerList = engineerList.stream()
                .filter(mtEngineer -> mtEngineer.getOrderNum().equals(minNum))
                .collect(Collectors.toList());
        if (dispatchEngineerList.isEmpty()) {
            return Result.error("无合适工程师");
        }
        int number = RandomUtils.nextInt(dispatchEngineerList.size());
        MtEngineer dispatchEngineer = dispatchEngineerList.get(number);
        // 工单数据补充
        mtRepairOrder.setProcessingStatus("1")//已派工
                .setSysOrgCode(dispatchEngineer.getSysOrgCode());//orgCode绑定
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 工程师数据装配
        mtRepairOrderPage.setMtRepairDispatchList(new ArrayList<>());
        MtRepairDispatch repairDispatch = new MtRepairDispatch();
        repairDispatch.setEngineerId(dispatchEngineer.getId())//绑定工程师
                .setProviderId(dispatchEngineer.getProviderId())//绑定服务商
                .setStationId(dispatchEngineer.getStationId())//绑定服务站
                .setDispatchTime(DateUtil.date())//派工时间
                .setWorkStatus(0)//工作状态默认值：未响应
                .setWorkType("负责");//人员类型：负责
        mtRepairOrderPage.getMtRepairDispatchList().add(repairDispatch);

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule repairSchedule = new MtRepairSchedule();
        repairSchedule.setScheduleStatus(1)//进度状态：派工
                .setScheduleTime(DateUtil.date())//进度时间
                .setEngnieerId(dispatchEngineer.getId());//工程师绑定
        // 进度描述装配
        repairSchedule.setRemarks(repairSchedule.getScheduleTime()
                + "  编号:" + mtRepairOrder.getOrderNo() + "的工单 自动分配给："
                + repairDispatch.getWorkType() + "-" + dispatchEngineer.getEngineerName() + "。");
        mtRepairOrderPage.getMtRepairScheduleList().add(repairSchedule);

        mtRepairOrderService.updateByWork(mtRepairOrderPage);
        return Result.OK("派工成功!");
    }


    /**
     * 手动派工
     *
     * @param wxRepairDispatchRequest
     * @return
     */
    @ApiOperation(value = "wechat-手动派工", notes = "wechat-手动派工")
    @PostMapping(value = "/dispatch")
    public Result<String> dispatch(@RequestBody WxRepairDispatchRequest wxRepairDispatchRequest) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        String remarksInfo = "";
        // 用户为服务商
        if (sysUser.getUserType() == 1) {
            remarksInfo = "服务商：" + sysUser.getRealname();// 进度跟踪描述：操作员字段装配
        }
        // 用户为工作站
        else if (sysUser.getUserType() == 2 || sysUser.getUserType() == 3) {
            remarksInfo = "服务站：" + sysUser.getRealname();// 进度跟踪描述：操作员字段装配
        }
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(wxRepairDispatchRequest.getOrderId());
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应数据");
        }
        if (!"0".equals(mtRepairOrder.getProcessingStatus())) {
            return Result.error("该工单已派工");
        }

        // 获取负责工程师数据
        MtEngineer dispatchEngineer = mtEngineerService.getById(wxRepairDispatchRequest.getDispatchEngineerId());
        // 工单数据更新
        mtRepairOrder.setProcessingStatus("1")//已派工
                .setSysOrgCode(dispatchEngineer.getSysOrgCode());//orgCode绑定
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 获取协助工程师数据
        List<MtEngineer> engineerList = mtEngineerService.list(new LambdaQueryWrapper<MtEngineer>()
                .in(MtEngineer::getId, Arrays.asList(wxRepairDispatchRequest.getDispatchEngineerIds().split(","))));
        // 工程师数据装配
        StringBuilder remarksEngineer = new StringBuilder();// 进度跟踪描述：工程师字段装配
        mtRepairOrderPage.setMtRepairDispatchList(new ArrayList<>());
        for (MtEngineer engineer : engineerList) {
            MtRepairDispatch repairDispatch = new MtRepairDispatch();
            repairDispatch.setEngineerId(engineer.getId())//绑定工程师
                    .setProviderId(engineer.getProviderId())//绑定服务商
                    .setStationId(engineer.getStationId())//绑定服务站
                    .setDispatchTime(DateUtil.date())//派工时间
                    .setWorkStatus(0)//工作状态默认值：未响应
                    .setWorkType(wxRepairDispatchRequest.getDispatchEngineerId().equals(engineer.getId()) ? "负责" : "协同");//人员类型
            mtRepairOrderPage.getMtRepairDispatchList().add(repairDispatch);
            remarksEngineer.append(repairDispatch.getWorkType()).append("-").append(engineer.getEngineerName()).append(" ");// 进度跟踪描述：工程师字段装配
        }

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(1)//进度状态：派工
                .setScheduleTime(DateUtil.date())//进度时间
                .setEngnieerId(dispatchEngineer.getId());//工程师绑定
        // 进度描述装配
        String remarks = mtRepairSchedule.getScheduleTime()
                + remarksInfo
                + "将编号:" + mtRepairOrder.getOrderNo() + "的工单 "
                + "分配给：" + remarksEngineer;
        mtRepairSchedule.setRemarks(remarks);
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.updateByWork(mtRepairOrderPage);
        return Result.OK("派工成功!");
    }


    /**
     * 撤销派工
     *
     * @param wxDispatchRequest
     * @return
     */
    @ApiOperation(value = "wechat-撤销派工", notes = "wechat-撤销派工")
    @PostMapping(value = "/cancelDispatch")
    public Result<String> cancelDispatch(@RequestBody WxDispatchRequest wxDispatchRequest) {

        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        String remarksInfo = "";
        // 用户为服务商
        if (sysUser.getUserType() == 1) {
            remarksInfo = "服务商：" + sysUser.getRealname();
        }
        // 用户为工作站
        else if (sysUser.getUserType() == 2 || sysUser.getUserType() == 3) {
            remarksInfo = "服务站：" + sysUser.getRealname();
        }
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(wxDispatchRequest.getOrderId());
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应数据");
        }
        if (!"1".equals(mtRepairOrder.getProcessingStatus())) {
            return Result.error("该工单无法撤销");
        }
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 更新派工记录
        if (!StrUtil.isBlank(wxDispatchRequest.getDispatchId())) {
            mtRepairOrderPage.setMtRepairDispatchList(new ArrayList<>());
            MtRepairDispatch dispatch = mtRepairDispatchService.getOne(new LambdaQueryWrapper<MtRepairDispatch>()
                    .eq(MtRepairDispatch::getId, wxDispatchRequest.getDispatchId()));
            dispatch.setWorkType("负责");
            mtRepairOrderPage.getMtRepairDispatchList().add(dispatch);
        }

        // 获取要删除的派工记录
        StringBuilder repair = new StringBuilder();
        List<MtRepairDispatch> deleteDispatch = mtRepairDispatchService.list(new LambdaQueryWrapper<MtRepairDispatch>()
                .in(MtRepairDispatch::getId, (Object[]) wxDispatchRequest.getDispatchIds().split(",")));
        // 派工记录进度描述装配
        for (MtRepairDispatch dispatch : deleteDispatch) {
            String engineerName = commonAPI.translateDictFromTable("mt_engineer", "engineer_name", "id", dispatch.getEngineerId());
            repair.append(dispatch.getWorkType()).append("-").append(engineerName);
        }

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(1)//进度状态：派工
                .setScheduleTime(DateUtil.date());//进度时间
        // 进度描述装配
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + remarksInfo
                + "将编号:" + mtRepairOrder.getOrderNo() + "的工单"
                + "中分配的：" + repair + "撤回");
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.repairOrderCancelDispatch(mtRepairOrderPage, deleteDispatch);
        return Result.OK("撤回成功!");
    }


    /**
     * 接单
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "wechat-接单", notes = "wechat-接单")
    @PutMapping(value = "/accept")
    public Result<String> accept(@RequestParam(name = "id", required = true) String id) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        // 获取登录工程师信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                .eq(MtEngineer::getUserId, loginUser.getUsername()));
        if (Objects.isNull(loginEngineer)) {
            return Result.error("未找到对应工程师");
        }

        // 派工记录数据更新
        mtRepairOrderPage.setMtRepairDispatchList(new ArrayList<>());
        List<MtRepairDispatch> repairDispatchList = mtRepairDispatchService.list(new LambdaQueryWrapper<MtRepairDispatch>()
                .eq(MtRepairDispatch::getOrderId, id));
        MtRepairDispatch repairDispatch = repairDispatchList.stream()
                .filter(mtRepairDispatch -> mtRepairDispatch.getEngineerId().equals(loginEngineer.getId()))
                .findFirst().orElse(null);
        if (Objects.isNull(repairDispatch)) {
            return Result.error("该工单未派工于该工程师");
        }
        if (repairDispatch.getWorkStatus() != 0) {
            return Result.error("该工程师已接单");
        }
        // 工程师数据装配
        repairDispatch.setWorkStatus(1);//工作状态：已接单
        mtRepairOrderPage.getMtRepairDispatchList().add(repairDispatch);

        // 获取工单数据
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(id);
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应工单");
        }
        // 工单数据更新
        boolean allMatch = repairDispatchList.stream().allMatch(mtRepairDispatch -> mtRepairDispatch.getWorkStatus() != 0);
        if (allMatch && "1".equals(mtRepairOrder.getProcessingStatus())) {
            mtRepairOrder.setProcessingStatus("2");//工单状态：已接单
        }
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(2)//进度状态：接单
                .setScheduleTime(DateUtil.date())//进度时间
                .setEngnieerId(loginEngineer.getId());//工程师绑定
        // 进度描述装配
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + " 工程师：" + repairDispatch.getWorkType() + "-" + loginEngineer.getEngineerName()
                + " 接收 编号:" + mtRepairOrder.getOrderNo() + "工单。");
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.updateByWork(mtRepairOrderPage);
        return Result.OK("接单成功!");
    }


    /**
     * 到店签到
     *
     * @param wxSignInRequest
     * @return
     */
    @ApiOperation(value = "wechat-到店签到", notes = "wechat-到店签到")
    @PostMapping(value = "/signIn")
    public Result<String> signIn(@RequestBody WxSignInRequest wxSignInRequest) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        // 获取登录工程师信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                .eq(MtEngineer::getUserId, loginUser.getUsername()));
        if (Objects.isNull(loginEngineer)) {
            return Result.error("未找到对应工程师");
        }
        // 获取工单派工记录
        mtRepairOrderPage.setMtRepairDispatchList(new ArrayList<>());
        List<MtRepairDispatch> repairDispatchList = mtRepairDispatchService.list(new LambdaQueryWrapper<MtRepairDispatch>()
                .eq(MtRepairDispatch::getOrderId, wxSignInRequest.getOrderId()));
        MtRepairDispatch repairDispatch = repairDispatchList.stream()
                .filter(mtRepairDispatch -> mtRepairDispatch.getEngineerId().equals(loginEngineer.getId()))
                .findFirst().orElse(null);
        if (Objects.isNull(repairDispatch)) {
            return Result.error("该工单未派工于该工程师");
        }
        if (repairDispatch.getWorkStatus() != 1) {
            return Result.error("该工程师已签到");
        }
        // 工单派工记录数据更新
        repairDispatch.setWorkStatus(2);//已签到
        mtRepairOrderPage.getMtRepairDispatchList().add(repairDispatch);

        // 获取工单数据
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(wxSignInRequest.getOrderId());
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应工单");
        }
        // 计算是否到店
        MtCustorm mtCustorm = mtCustormService.getById(mtRepairOrder.getCustomId());
        //longitudeA 第一个点的经度
        //latitudeA  第一个点的纬度
        String[] croods = StringUtils.split(mtCustorm.getCrood(), ",");
        double longitudeA = Double.parseDouble(croods[0]);
        double latitudeA = Double.parseDouble(croods[1]);
        //longitudeB 第二个点的经度
        //latitudeB  第二个点的纬度
        String[] croodsB = StringUtils.split(wxSignInRequest.getSignInCrood(), ",");
        double longitudeB = Double.parseDouble(croodsB[0]);
        double latitudeB = Double.parseDouble(croodsB[1]);
        boolean inCircle = PositionUtil.isInCircle(longitudeA, latitudeA, longitudeB, latitudeB, "500");
        if (!inCircle) {
            return Result.error("尚未到达店铺");
        }

        // 工单数据更新
        boolean allMatch = repairDispatchList.stream().allMatch(mtRepairDispatch -> mtRepairDispatch.getWorkStatus() != 1);
        if (allMatch && "2".equals(mtRepairOrder.getProcessingStatus())) {
            mtRepairOrder.setProcessingStatus("3");//处理中
        }
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(3)//进度状态：处理中
                .setScheduleTime(DateUtil.date())//进度时间
                .setEngnieerId(loginEngineer.getId());//工程师绑定
        // 进度描述装配
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + " 工程师：" + repairDispatch.getWorkType() + "-" + loginEngineer.getEngineerName()
                + " 于编号:" + mtRepairOrder.getOrderNo() + "工单进行签到");
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.updateByWork(mtRepairOrderPage);
        return Result.OK("签到成功!");
    }


    /**
     * 添加处理记录
     *
     * @param wxRepairDisposeRequest
     * @return
     */
    @ApiOperation(value = "wechat-添加处理记录", notes = "wechat-添加处理记录")
    @PostMapping(value = "/addDispose")
    public Result<String> addDispose(@RequestBody WxRepairDisposeRequest wxRepairDisposeRequest) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        // 获取登录工程师信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                .eq(MtEngineer::getUserId, loginUser.getUsername()));
        if (Objects.isNull(loginEngineer)) {
            return Result.error("未找到对应工程师");
        }
        // 获取工单数据
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(wxRepairDisposeRequest.getOrderId());
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应工单");
        }
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 派工记录数据更新
        MtRepairDispatch loginDispatch = mtRepairDispatchService.getOne(new LambdaQueryWrapper<MtRepairDispatch>()
                .eq(MtRepairDispatch::getOrderId, mtRepairOrder.getId())
                .eq(MtRepairDispatch::getEngineerId, loginEngineer.getId()));
        mtRepairOrderPage.setMtRepairDispatchList(new ArrayList<>());
        loginDispatch.setWorkStatus(3)//工作状态：已处理
                .setCompletionTime(DateUtil.date());//完工时间
        mtRepairOrderPage.getMtRepairDispatchList().add(loginDispatch);

        // 处理报告数据装配
        mtRepairOrderPage.setMtRepairDisposeList(new ArrayList<>());
        MtRepairDispose mtRepairDispose = new MtRepairDispose();
        mtRepairDispose.setEngineerId(loginEngineer.getId())//工程师
                .setDisposeTime(DateUtil.date())//报告时间
                .setDisposeRemarks(wxRepairDisposeRequest.getDisposeRemarks())//报告描述
                .setDisposePhoto(wxRepairDisposeRequest.getDisposePhoto())//照片
                .setStationId(loginEngineer.getStationId())//报告工程师所属服务站
                .setProviderId(loginEngineer.getProviderId())//报告工程师所属服务商
                .setDisposeStatus("3");//报告状态：处理中
        mtRepairOrderPage.getMtRepairDisposeList().add(mtRepairDispose);

        // 处理设备数据装配
        mtRepairOrderPage.setMtRepairEquipList(new ArrayList<>());
        for (WxRepairEquip repairEquip : wxRepairDisposeRequest.getWxRepairEquipList()) {
            MtRepairEquip mtRepairEquip = new MtRepairEquip();
            mtRepairEquip.setCustomId(mtRepairOrder.getCustomId())//客户绑定
                    .setCustomEquipId(repairEquip.getCustomEquipId())//客户设备绑定
                    .setSubmissTime(DateUtil.date())//提报时间
                    .setOrderType(mtRepairOrder.getSkillType())//工单类型
                    .setEngineerId(loginEngineer.getId())//工程师绑定
                    .setProviderId(loginEngineer.getProviderId())//服务商绑定
                    .setStationId(loginEngineer.getStationId())//服务站绑定
                    .setEquipId(repairEquip.getEquipId())//设备绑定
                    .setSolutionPhoto(repairEquip.getSolutionPhoto())//处理过程照片
                    .setDisposeStyle(repairEquip.getDisposeStyle())//处理方式
                    .setSolution(repairEquip.getSolution())//解决方案
                    .setProblemPhoto(repairEquip.getProblemPhoto())//问题图片
                    .setRemarks(repairEquip.getRemarks())//问题描述
                    .setNewEquipId(repairEquip.getNewEquipId())//更换设备
                    .setNewEquipCode(repairEquip.getNewEquipCode());//新设备编码
            mtRepairOrderPage.getMtRepairEquipList().add(mtRepairEquip);
        }

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(3)//进度状态：处理中
                .setScheduleTime(DateUtil.date())//进度时间
                .setEngnieerId(loginEngineer.getId());//工程师绑定
        // 进度描述装配
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + " 工程师：" + loginEngineer.getEngineerName()
                + " 为编号:" + mtRepairOrder.getOrderNo() + "工单提交处理汇报。");
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.updateByWork(mtRepairOrderPage);
        return Result.OK("提交成功!");
    }


    /**
     * 修改处理记录
     *
     * @param wxRepairDisposeRequest
     * @return
     */
    @ApiOperation(value = "wechat-修改处理记录", notes = "wechat-修改处理记录")
    @PutMapping(value = "/editDispose")
    public Result<String> editDispose(@RequestBody WxRepairDisposeRequest wxRepairDisposeRequest) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        // 获取登录工程师信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                .eq(MtEngineer::getUserId, loginUser.getUsername()));
        if (Objects.isNull(loginEngineer)) {
            return Result.error("未找到对应工程师");
        }
        // 获取工单数据
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(wxRepairDisposeRequest.getOrderId());
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应工单");
        }
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 处理报告数据装配
        mtRepairOrderPage.setMtRepairDisposeList(new ArrayList<>());
        MtRepairDispose repairDispose = mtRepairDisposeService.getById(wxRepairDisposeRequest.getId());
        repairDispose.setDisposeRemarks(wxRepairDisposeRequest.getDisposeRemarks())//报告描述
                .setDisposePhoto(wxRepairDisposeRequest.getDisposePhoto());//照片
        mtRepairOrderPage.getMtRepairDisposeList().add(repairDispose);

        // 处理设备数据装配
        mtRepairOrderPage.setMtRepairEquipList(new ArrayList<>());
        List<MtRepairEquip> repairEquipList = mtRepairEquipService.list(new LambdaQueryWrapper<MtRepairEquip>()
                .eq(MtRepairEquip::getOrderId, wxRepairDisposeRequest.getOrderId())
                .eq(MtRepairEquip::getEngineerId, loginEngineer.getId()));
        for (WxRepairEquip wxRepairEquip : wxRepairDisposeRequest.getWxRepairEquipList()) {
            MtRepairEquip repairEquip = repairEquipList.stream().filter(equip -> equip.getId().equals(wxRepairEquip.getId())).findAny().orElse(new MtRepairEquip());
            if (StrUtil.isBlank(repairEquip.getId())) {
                repairEquip.setCustomId(mtRepairOrder.getCustomId())//客户绑定
                        .setCustomEquipId(wxRepairEquip.getCustomEquipId())//客户设备绑定
                        .setSubmissTime(DateUtil.date())//提报时间
                        .setOrderType(mtRepairOrder.getSkillType())//工单类型
                        .setEngineerId(loginEngineer.getId())//工程师绑定
                        .setProviderId(loginEngineer.getProviderId())//服务商绑定
                        .setStationId(loginEngineer.getStationId())//服务站绑定
                        .setEquipId(wxRepairEquip.getEquipId())//设备绑定
                        .setSolutionPhoto(wxRepairEquip.getSolutionPhoto())//处理过程照片
                        .setDisposeStyle(wxRepairEquip.getDisposeStyle())//处理方式
                        .setSolution(wxRepairEquip.getSolution())//解决方案
                        .setProblemPhoto(wxRepairEquip.getProblemPhoto())//问题图片
                        .setRemarks(wxRepairEquip.getRemarks())//问题描述
                        .setNewEquipId(wxRepairEquip.getNewEquipId())//更换设备
                        .setNewEquipCode(wxRepairEquip.getNewEquipCode());//新设备编码
            } else {
                repairEquip.setSolutionPhoto(wxRepairEquip.getSolutionPhoto())//处理过程照片
                        .setDisposeStyle(wxRepairEquip.getDisposeStyle())//处理方式
                        .setSolution(wxRepairEquip.getSolution())//解决方案
                        .setProblemPhoto(wxRepairEquip.getProblemPhoto())//问题图片
                        .setRemarks(wxRepairEquip.getRemarks())//问题描述
                        .setNewEquipId(wxRepairEquip.getNewEquipId())//更换设备
                        .setNewEquipCode(wxRepairEquip.getNewEquipCode());//新设备编码
            }
            mtRepairOrderPage.getMtRepairEquipList().add(repairEquip);
        }

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(3)//进度状态：处理中
                .setScheduleTime(DateUtil.date())//进度时间
                .setEngnieerId(loginEngineer.getId());//工程师绑定
        // 进度描述装配
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + " 工程师：" + loginEngineer.getEngineerName()
                + " 将编号:" + mtRepairOrder.getOrderNo() + "工单的处理记录进行修改。");
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.updateByWork(mtRepairOrderPage);
        return Result.OK("修改成功!");
    }


    /**
     * 完工
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "wechat-完工", notes = "wechat-完工")
    @PutMapping(value = "/complete")
    public Result<String> complete(@RequestParam(name = "id", required = true) String id) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        // 获取登录工程师信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                .eq(MtEngineer::getUserId, loginUser.getUsername()));
        if (Objects.isNull(loginEngineer)) {
            return Result.error("未找到对应工程师");
        }

        // 获取工单数据
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(id);
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应工单");
        }
        // 工单数据更新
        mtRepairOrder.setProcessingStatus("4")//工单状态：处理完毕待客户确认
                .setUpdateCustomEquip(true);//开启客户设备更新业务
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(4)//进度状态：待客户确认
                .setScheduleTime(DateUtil.date())//进度时间
                .setEngnieerId(loginEngineer.getId());//工程师绑定
        // 进度描述装配
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + " 工程师：" + "负责-" + loginEngineer.getEngineerName()
                + " 完成了编号:" + mtRepairOrder.getOrderNo() + "工单的处理。");
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.updateByWork(mtRepairOrderPage);
        return Result.OK("工单完成!待客户确认");
    }


    /**
     * 客户评价
     *
     * @param wxRepairFeedbackRequest
     * @return
     */
    @ApiOperation(value = "wechat-客户评价", notes = "wechat-客户评价")
    @PostMapping(value = "/evaluate")
    public Result<String> evaluate(@RequestBody WxRepairFeedbackRequest wxRepairFeedbackRequest) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        // 获取登录工程师信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MtCustorm loginCustorm = mtCustormService.getOne(new LambdaQueryWrapper<MtCustorm>()
                .eq(MtCustorm::getUserId, loginUser.getUsername()));
        if (Objects.isNull(loginCustorm)) {
            return Result.error("未找到对应客户");
        }
        // 获取工单数据
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(wxRepairFeedbackRequest.getOrderId());
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应工单");
        }
        // 工单数据更新
        mtRepairOrder.setProcessingStatus("5");//已完成
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 反馈评价数据装配
        mtRepairOrderPage.setMtRepairFeedbackList(new ArrayList<>());
        MtRepairFeedback repairFeedback = new MtRepairFeedback();
        repairFeedback.setSatisfaction(wxRepairFeedbackRequest.getSatisfaction())//满意度
                .setAttitude(wxRepairFeedbackRequest.getAttitude())//服务态度
                .setEfficiency(wxRepairFeedbackRequest.getEfficiency())//服务效率
                .setQuality(wxRepairFeedbackRequest.getQuality())//服务质量
                .setProductSatisfaction(wxRepairFeedbackRequest.getProductSatisfaction())//产品满意度
                .setQuickEvaluation(wxRepairFeedbackRequest.getQuickEvaluation())//评价
                .setBackPhoto(wxRepairFeedbackRequest.getBackPhoto())//照片
                .setRemarks(wxRepairFeedbackRequest.getRemarks())//备注
                .setBackTime(DateUtil.date())//评价时间
                .setCustomId(mtRepairOrder.getCustomId());//评价客户
        mtRepairOrderPage.getMtRepairFeedbackList().add(repairFeedback);

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(5)//进度状态：完成
                .setScheduleTime(DateUtil.date());//进度时间
        // 进度描述装配
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + " 客户：" + loginCustorm.getCustormName() + "为 "
                + " 编号:" + mtRepairOrder.getOrderNo() + "的工单 "
                + " 提交评价。");
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.updateByWork(mtRepairOrderPage);
        return Result.OK("评价成功!");
    }


    /**
     * 回访
     *
     * @param wxRepairVisitRequest
     * @return
     */
    @ApiOperation(value = "wechat-回访", notes = "wechat-回访")
    @PostMapping(value = "/feedback")
    public Result<String> feedback(@RequestBody WxRepairVisitRequest wxRepairVisitRequest) {
        MtRepairOrderPage mtRepairOrderPage = new MtRepairOrderPage();
        // 获取登录工程师信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        String remarksInfo = "";
        // 用户为服务商
        if (sysUser.getUserType() == 1) {
            MtServiceProviders loginProviders = mtServiceProvidersService.getOne(new LambdaQueryWrapper<MtServiceProviders>()
                    .eq(MtServiceProviders::getUserId, loginUser.getUsername()));
            if (Objects.isNull(loginProviders)) {
                return Result.error("未找到对应服务商");
            }
            remarksInfo = "服务商：" + loginProviders.getProName();
        }
        // 用户为工作站
        else if (sysUser.getUserType() == 2) {
            MtServiceStation loginStation = mtServiceStationService.getOne(new LambdaQueryWrapper<MtServiceStation>()
                    .eq(MtServiceStation::getUserId, loginUser.getUsername()));
            if (Objects.isNull(loginStation)) {
                return Result.error("未找到对应工作站");
            }
            remarksInfo = "工作站：" + loginStation.getStationName();
        } else {
            return Result.error("该用户非服务商/服务站");
        }

        // 获取工单数据
        MtRepairOrder mtRepairOrder = mtRepairOrderService.getById(wxRepairVisitRequest.getOrderId());
        if (Objects.isNull(mtRepairOrder)) {
            return Result.error("未找到对应工单");
        }
        // 工单数据更新
        mtRepairOrder.setProcessingStatus("6");//已归档
        BeanUtils.copyProperties(mtRepairOrder, mtRepairOrderPage);

        // 回访记录数据装配
        mtRepairOrderPage.setMtRepairVisitList(new ArrayList<>());
        MtRepairVisit repairVisit = new MtRepairVisit();
        repairVisit.setProviderId(mtRepairOrder.getProviderId())//服务商
                .setStationId(mtRepairOrder.getStationId())//服务站
                .setFeedbackTime(DateUtil.date())//回访时间
                .setSatisfaction(wxRepairVisitRequest.getSatisfaction())//满意度
                .setRemarks(wxRepairVisitRequest.getRemarks())//备注
                .setCustomId(mtRepairOrder.getCustomId())//客户
                .setFeedbackUser(loginUser.getUsername());//回访人
        mtRepairOrderPage.getMtRepairVisitList().add(repairVisit);

        // 进度跟踪数据装配
        mtRepairOrderPage.setMtRepairScheduleList(new ArrayList<>());
        MtRepairSchedule mtRepairSchedule = new MtRepairSchedule();
        mtRepairSchedule.setScheduleStatus(6)//进度状态：归档
                .setScheduleTime(DateUtil.date());//进度时间
        // 进度描述装配
        mtRepairSchedule.setRemarks(mtRepairSchedule.getScheduleTime()
                + remarksInfo
                + "对编号:" + mtRepairOrder.getOrderNo() + "的工单"
                + "回访完成，进行归档。");
        mtRepairOrderPage.getMtRepairScheduleList().add(mtRepairSchedule);

        mtRepairOrderService.updateByWork(mtRepairOrderPage);
        return Result.OK("回访完成!");
    }

    /**
     * 根据工单id获取登录工程师派工记录
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据工单id获取登录工程师派工记录", notes = "根据工单id获取登录工程师派工记录")
    @GetMapping(value = "/getLoginRepairDispatchByOrderId")
    public Result getLoginRepairDispatchByOrderId(@RequestParam(name = "id", required = true) String id) {
        // 获取登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        // 用户为工程师
        if (sysUser.getUserType() == 3) {
            MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                    .eq(MtEngineer::getUserId, sysUser.getUsername()));
            MtRepairDispatch repairDispatch = mtRepairDispatchService.getOne(new LambdaQueryWrapper<MtRepairDispatch>()
                    .eq(MtRepairDispatch::getOrderId, id)
                    .eq(MtRepairDispatch::getEngineerId, loginEngineer.getId()));
            return Result.OK(repairDispatch);
        }
        return Result.OK();
    }

    /**
     * 根据工单id获取登录工程师处理记录
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据工单id获取登录工程师处理记录", notes = "根据工单id获取登录工程师处理记录")
    @GetMapping(value = "/getLoginRepairDisposeByOrderId")
    public Result getLoginRepairDisposeByOrderId(@RequestParam(name = "id", required = true) String id) {
        // 获取登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        // 用户为工程师
        if (sysUser.getUserType() == 3) {
            MtEngineer loginEngineer = mtEngineerService.getOne(new LambdaQueryWrapper<MtEngineer>()
                    .eq(MtEngineer::getUserId, sysUser.getUsername()));
            MtRepairDispose repairDispose = mtRepairDisposeService.getOne(new LambdaQueryWrapper<MtRepairDispose>()
                    .eq(MtRepairDispose::getOrderId, id)
                    .eq(MtRepairDispose::getEngineerId, loginEngineer.getId()));
            return Result.OK(repairDispose);
        }
        return Result.OK();
    }


    /****************************************************工单部分接口结束***************************************************/

}
